/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.iboss.service.sc;

import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.OrderSyncStatusConstant;
import net.dgg.dggcloud.service.iboss.constant.RemarkOperationConstant;
import net.dgg.dggcloud.service.iboss.constant.ScOperationConstant;
import net.dgg.dggcloud.service.iboss.constant.ScStatusConstant;
import net.dgg.dggcloud.service.iboss.dao.sc.AbolishDao;
import net.dgg.dggcloud.service.iboss.dao.sc.UserReadDao;
import net.dgg.dggcloud.service.iboss.entity.ScProFlowOperating;
import net.dgg.dggcloud.service.iboss.entity.ScProOrder;
import net.dgg.dggcloud.service.iboss.entity.ScProOrderTimeState;
import net.dgg.dggcloud.service.iboss.service.common.ChargeBackService;
import net.dgg.dggcloud.service.iboss.utils.DataWrap;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import net.dgg.dggcloud.service.jrcrm.service.cms.MessageService;
import net.dgg.dggcloud.service.jrcrm.service.orf.api.OrderApiService;
import net.dgg.dggcloud.service.service.user.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;


/**
 * @class_name: AbolishDao
 * @package: net.dgg.dggcloud.service.iboss.service.sc
 * @describe: TODO
 * @creat_user: 孙上峰
 * @creat_date: 2017/11/29
 * @creat_time: 14:50
 **/
@Service
public class AbolishService extends BaseService {
    @Resource
    private AbolishDao abolishDao;
    @Autowired
    private OrderApiService orderApiService;
    @Autowired
    private ScProOrderService scProOrderService;
    @Resource
    private UserService userService;
    @Autowired
    private UserReadDao userReadDao;
    @Autowired
    private ChargeBackService chargeBackService;
    @Resource
    private MessageService messageService;
    @Resource
    private ScProOrderTimeStateService scProOrderTimeStateService;
    @Resource
    private CustomerRecordService customerRecordService;
    @Resource
    private AllProOrderService allProOrderService;
    @Autowired
    private WaitAllocationService waitAllocationService;

    /**
     * 废单审核中
     *
     * @param map
     * @return
     */
    public List<Map> listAbolishByMap(Map map) {
        return abolishDao.listAbolishByMap(map);
    }

    public Integer countAbolishByMap(Map map) {
        return abolishDao.countAbolishByMap(map);
    }

    /**
     * 同意废单/退单
     *
     * @param ids
     * @param type
     */
    public void updateAbolitionConsent(String ids, String type, String remark) {
        Assert.hasText(ids, "订单ID不能为空！");
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        List<Long> idList = new ArrayList<>();
        String[] idArr = ids.replaceAll(" ", "").split(",");
        ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
        for (String t : idArr) {
            idList.add(Long.valueOf(t));
        }
        for (Long id : idList) {
            ScProOrder scProOrder = scProOrderService.getById(id);
            Assert.isTrue(scProOrder.getAuditorId().equals(user.getId()), "您不是当前审核人,不能审核该订单！");
            Integer status = scProOrder.getAuditStatus();
            if (scProOrder == null) {
                continue;
            }
            User user1 = userService.getUserById(scProOrder.getFlowUserId()); //流程人员信息
            Assert.notNull(user1, "没有查询到流程人员的信息！");
            Assert.notNull(scProOrder.getSigningUserId(), "没有查询到签单商务人员的信息！");
            User receiverUser = null;
            if (status == 1) {
                scProOrder.setAuditorId(scProOrder.getSigningUserId());
                scProOrder.setAuditorName(scProOrder.getSigningUserName());
                scProOrder.setAuditStatus(2);//该商务审核
                if (type.equals("1")) { //废单
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ABANDON_AUDIT);//废单审核中
                    scProFlowOperating.setOperation("流程主管审核废单通过");
                } else {
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_RETURENED_AUDIT);//退单审核中
                    scProFlowOperating.setOperation("流程主管审核退单通过");
                }
                receiverUser = chargeBackService.queryAuditUser(scProOrder.getAuditorId());//查找推送信息接收人

            } else if (status == 2) { //证明是该商务人员审核的
                 /*获取部门主管或商务经理的信息*/
                // Map map = auditPerson(user1.getId(), scProOrder.getAuditStatus());
                    /*根据流程人员获取对应的leader数据*/
                Map map = auditPerson(user.getOrgId(), status);
                if (map != null) {
                    scProOrder.setAuditorId(Long.valueOf(String.valueOf(map.get("id"))));
                    scProOrder.setAuditorName(String.valueOf(map.get("name")));
                    scProOrder.setNotes(remark);
                    scProOrder.setAuditStatus(3); //商务经理审核
                    if (type.equals("1")) { //废单
                        scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ABANDON_AUDIT);//废单审核中
                        scProFlowOperating.setOperation("商务审核废单通过");
                    } else {
                        scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_RETURENED_AUDIT);//退单审核中
                        scProFlowOperating.setOperation("商务审核退单通过");
                    }
                    receiverUser = chargeBackService.queryAuditUser(scProOrder.getAuditorId());//查找推送信息接收人
                }
            }
            //证明是商务经理审核
            if (status == 3) {
                //审核完成，改变生产订单状态
                if (type.equals("1")) { //废单
                    scProOrder.setStatus(ScStatusConstant.ORDER_ANANDON);
                    //废单时同步到CRM,新增渠道的订单不进行同步
                    if (scProOrder.getOrderBusId() != null && !scProOrder.getOrderBusId().equals("")) {
                        Map<String, Object> datas = new HashMap<>();
                        datas.put("mainOrderId", scProOrder.getOrderId());//销售主订单id
                        datas.put("childOrderId", scProOrder.getOrderBusId());//销售子订单id
                        datas.put("orderStatus", "ORF_BDZT_3");//状态 ORF_BDZT_1:成单  ORF_BDZT_2 :退单   ORF_BDZT_3:废单  ORF_BDZT_4:暂缓   ORF_BDZT_5:生产中
                        datas.put("currentUser", user);
                        orderApiService.synOrderState(datas);
                    }
                } else { //退单
                    scProOrder.setStatus(ScStatusConstant.ORDER_RETURENED);
                    //退单时同步到CRM,新增渠道的订单不进行同步
                    if (scProOrder.getOrderBusId() != null && !scProOrder.getOrderBusId().equals("")) {
                        Map<String, Object> datas = new HashMap<>();
                        datas.put("mainOrderId", scProOrder.getOrderId());//销售主订单id
                        datas.put("childOrderId", scProOrder.getOrderBusId());//销售子订单id
                        datas.put("orderStatus", "ORF_BDZT_2");//状态 ORF_BDZT_1:成单  ORF_BDZT_2 :退单   ORF_BDZT_3:废单  ORF_BDZT_4:暂缓   ORF_BDZT_5:生产中
                        datas.put("currentUser", user);
                        orderApiService.synOrderState(datas);
                    }
                }
                if (type.equals("1")) { //废单
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ABANDON_AUDIT);//废单审核中
                    scProFlowOperating.setOperation("商务经理审核废单通过");
                } else {
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_RETURENED_AUDIT);//退单审核中
                    scProFlowOperating.setOperation("商务经理审核退单通过");
                }
                ScProOrderTimeState state = this.repository.get(ScProOrderTimeState.class, scProOrder.getId());
                if (state != null) { //接受过
                    scProOrderTimeStateService.update_suspendScProOrderTime(scProOrder.getId()); //停止计算时间
                }

            }
            DataWrap.updateWraps(scProOrder); //更新操作人信息
            //操作记录
            /*拿到上一条记录的id*/
            ScProFlowOperating scProFlowOperating1 = this.repository.get(ScProFlowOperating.class, scProOrder.getFlowLatestOperationId());

            scProFlowOperating.setId(this.keyWorker.nextId());
            scProOrder.setFlowLatestOperationId(scProFlowOperating.getId()); //设置最新的ID
            scProFlowOperating.setProProductId(scProOrder.getId());
            scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
            scProFlowOperating.setFlowUserId(user.getId());
            scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
            scProFlowOperating.setStatus(scProOrder.getStatus());
            DataWrap.saveWrap(scProFlowOperating);
            if (scProFlowOperating1 != null) { //获取申请退单废单备注
                scProFlowOperating.setRemark(scProFlowOperating1.getRemark()); //废单退单code
                scProFlowOperating.setRemarkInfo(remark); // 审核通过原因
                scProFlowOperating.setReturnOrAbandonTime(scProFlowOperating1.getReturnOrAbandonTime());  //废单退单时间
                scProFlowOperating.setReturnOrAbandonRemark(scProFlowOperating1.getRemarkInfo()); //废单退单详情
            }
            this.repository.saveOrUpdate(scProOrder);
            this.repository.save(scProFlowOperating);
            if(receiverUser!=null){
                if (type.equals("1")) { //废单
                    String[] vals = new String[1];
                    vals[0] = String.valueOf(scProOrder.getOrderBusinessNo());
                    String tempCode = "SC_DSH_MSG";
                    String tem = "订单{0}需要审核，请及时查看";
                    messageService.sendMessageReady(receiverUser, user, vals, tempCode);//消息提醒
                } else if (type.equals("2")) { //退单
                    String[] vals = new String[1];
                    vals[0] = String.valueOf(scProOrder.getOrderBusinessNo());
                    String tempCode = "SC_TD_MSG";
                    String tem = "订单{0}需要审核，请及时查看";
                    messageService.sendMessageReady(receiverUser, user, vals, tempCode);//消息提醒
                }
            }


        }
    }

    /**
     * 获取废单/退单当前审核人
     *
     * @param orgid
     * @return
     */
    /*public Map auditPerson(Long orgid, Integer state) {
        Map map = new HashMap();
        Map map1 = null;
        if (orgid != null && state == 1) { //流程主管审核
            map.put("flowId", String.valueOf(orgid));
            map1 = userReadDao.getAuditPerson(map);
            Assert.notNull(map1, "没有查询到该流程人员主管的信息！");
        }
        if (orgid != null && state == 2) { //商务经理审核
            map.put("managerId", String.valueOf(orgid));
            map1 = userReadDao.getAuditPerson(map);
            Assert.notNull(map1, "没有查询到商务经理的信息！");
        }
        return map1;
    }*/

    /**
     * @param orgid 流程人员组织架构id
     * @return
     */
    public Map auditPerson(Long orgid, Integer state) {
        Map map = new HashMap();
        Map map1 = null;
        if (orgid != null) { //流程主管审核
            map.put("orgid", String.valueOf(orgid));
            map1 = userReadDao.getLeaderPerson(map);
            if (state == 1) {
                Assert.notNull(map1, "没有查询到该流程人员主管的信息！");
            } else {
                Assert.notNull(map1, "没有查询到该商务的商务经理的信息！");
            }
        }
        return map1;
    }

    /**
     * 撤回废单/退单操作
     *
     * @param ids
     * @param type
     */
    public void updateToWithdraw(String ids, String type) {
        Assert.hasText(ids, "订单ID不能为空！");
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        List<Long> idList = new ArrayList<>();
        String[] idArr = ids.replaceAll(" ", "").split(",");
        for (String t : idArr) {
            idList.add(Long.valueOf(t));
        }
        for (Long id : idList) {
            ScProOrder scProOrder = scProOrderService.getById(id);
            if (scProOrder == null) {
                continue;
            }
            Assert.isTrue(scProOrder.getFlowUserId().equals(user.getId()), "您不是该生产订单的流程人员,不能进行该操作!");
            Assert.isTrue(!scProOrder.getStatus().equals(ScStatusConstant.ORDER_PROCESS), "改生产订单状态已改变,不能进行该操作,请刷新界面！");
            scProOrder.setStatus(ScStatusConstant.ORDER_PROCESS); //办理中
            DataWrap.updateWraps(scProOrder); //更新操作人信息

            //操作记录
            ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
            scProFlowOperating.setProProductId(scProOrder.getId());
            scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
            scProFlowOperating.setFlowUserId(user.getId());
            scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
            scProFlowOperating.setStatus(scProOrder.getStatus());
            Date curDate = new Date();
            DataWrap.saveWrap(scProFlowOperating);
            scProFlowOperating.setId(this.keyWorker.nextId());
            scProOrder.setFlowLatestOperationId(scProFlowOperating.getId());
            this.repository.save(scProFlowOperating);
            this.repository.saveOrUpdate(scProOrder);
            waitAllocationService.updateUserSetting(scProOrder, "2"); //加1
            Map recordMap = new HashMap();
            if (type.equals("1")) {
                scProFlowOperating.setOperation("废单撤回");
                ScProOrderTimeState state = this.repository.get(ScProOrderTimeState.class, scProOrder.getId());
                scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_FD_BACK); //废单撤回
                recordMap.put("content", "废单撤回");//备注内容
                recordMap.put("recordType", RemarkOperationConstant.REMARK_ORDER_ABOLISH);//备注类型
                if (state == null) { // 为空 表示是从待接收的废单
                    scProOrder.setOrderTime(curDate); //设置接单时间
                    Map map = this.scProOrderTimeStateService.addScProOrderTimeState(scProOrder); // 创建超期数据
                    try {
                        this.allProOrderService.saveUpdateNodeInfo(map, user);
                    } catch (Exception e) {
                        String msg = e.getMessage();
                        Assert.isTrue(false, StringUtils.isEmpty(msg) ? "系统出现异常！" : msg);
                    }
                }
            } else {
                scProFlowOperating.setOperation("退单撤回");
                recordMap.put("recordType", RemarkOperationConstant.REMARK_ORDER_SENDBACK);//备注类型
                scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_TD_BACK); //退单撤回
                recordMap.put("content", "退单撤回");//备注内容
            }
            //同步备注到crm
            recordMap.put("tableName", ScProOrder.TABLE_NAME);
            recordMap.put("tableId", scProOrder.getId());
            recordMap.put("cusId", scProOrder.getCustomerId());
            recordMap.put("operateUser", user.getId());//当前操作人id
            recordMap.put("ext3", scProOrder.getOrderBusinessNo()); //生产编号
            customerRecordService.saveCustomerRecord(recordMap);//写入crm
            //非新增渠道子订单 同步状态数据
            if (scProOrder.getOrderId() != null && scProOrder.getOrderBusId() != null) {
                Map<String, Object> pMap = new HashMap<>();
                pMap.put("mainOrderId", String.valueOf(scProOrder.getOrderId()));
                pMap.put("childOrderId", String.valueOf(scProOrder.getOrderBusId()));
                pMap.put("orderStatus", OrderSyncStatusConstant.ORF_BDZT_5); // ORF_BDZT_5
                this.orderApiService.synOrderState(pMap);
            }

        }
    }


    /**
     * 驳回生产订单
     */
    public void updateRejected(String ids, String type, String remark) {
        Assert.hasText(ids, "订单ID不能为空！");
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        List<Long> idList = new ArrayList<>();
        String[] idArr = ids.replaceAll(" ", "").split(",");
        for (String t : idArr) {
            idList.add(Long.valueOf(t));
        }
        for (Long id : idList) {
            ScProOrder scProOrder = scProOrderService.getById(id);
            Assert.isTrue(scProOrder.getAuditorId().equals(user.getId()), "您不是当前审核人,不能审核该订单！");
            if (scProOrder == null) {
                continue;
            }
            if (type.equals("1")) { //废单驳回
                scProOrder.setStatus(ScStatusConstant.ABANDON_REFUSE);
            } else {//退单驳回
                scProOrder.setStatus(ScStatusConstant.RETURENED_REFUSE);
            }
            scProOrder.setNotes(remark);
            DataWrap.updateWraps(scProOrder); //更新操作人信息

            //操作记录
            ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
            ScProFlowOperating scProFlowOperating1 = this.repository.get(ScProFlowOperating.class, scProOrder.getFlowLatestOperationId());
            if (scProFlowOperating1 != null) {
                scProFlowOperating.setRemarkInfo(remark);//驳回原因
                scProFlowOperating.setRemark(scProFlowOperating1.getRemark());
                scProFlowOperating.setReturnOrAbandonRemark(scProFlowOperating1.getRemarkInfo());  //退单原因
                scProFlowOperating.setReturnOrAbandonTime(scProFlowOperating1.getReturnOrAbandonTime()); //退单或废单时间
            }
            scProFlowOperating.setProProductId(scProOrder.getId());
            scProFlowOperating.setProProductNo(scProOrder.getOrderBusinessNo());
            scProFlowOperating.setFlowUserId(user.getId());
            scProFlowOperating.setFlowUserName(scProOrder.getFlowUserName());
            scProFlowOperating.setStatus(scProOrder.getStatus());
            scProFlowOperating.setRefusePerson(user.getName());
            // scProFlowOperating.setRemarkInfo(remark); //驳回原因
            if (scProOrder.getAuditStatus() == 1) { //流程主管驳回
                if (type.equals("1")) {
                    scProFlowOperating.setOperation("流程主管废单驳回");
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_ABANDON_APPLY);
                } else {
                    scProFlowOperating.setOperation("流程主退单驳回");
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_RETURENED);
                }
            }
            if (scProOrder.getAuditStatus() == 2) { //商务驳回
                if (type.equals("1")) {
                    scProFlowOperating.setOperation("商务废单驳回");
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_ABANDON_APPLY);
                } else {
                    scProFlowOperating.setOperation("商务退单驳回");
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_RETURENED);
                }
            }
            if (scProOrder.getAuditStatus() == 3) { //商务驳回
                if (type.equals("1")) {
                    scProFlowOperating.setOperation("商务经理废单驳回");
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_ABANDON_APPLY);
                } else {
                    scProFlowOperating.setOperation("商务经理退单驳回");
                    scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_RETURENED);
                }
            }
            DataWrap.saveWrap(scProFlowOperating);
            scProFlowOperating.setId(this.keyWorker.nextId());
            scProOrder.setFlowLatestOperationId(scProFlowOperating.getId());
            this.repository.saveOrUpdate(scProOrder);
            this.repository.save(scProFlowOperating);

        }
    }

    /**
     * 更换审核人
     *
     * @param ids
     */
    public void updateAuditor(String ids, String auditorsUserId) {
        Assert.hasText(ids, "订单ID不能为空！");
        Assert.hasText(auditorsUserId, "审核人id为空！");
        User user = SessionManager.getCurrentUser();
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");
        ScProOrder scProOrder = scProOrderService.getById(Long.valueOf(ids));
        Assert.isTrue(scProOrder.getFlowUserId().equals(user.getId()), "您不是该订单的流程人员,不能更换审核人！");
        User auditorsUser = userService.getUserById(Long.valueOf(auditorsUserId));
        Assert.notNull(auditorsUser, "审核人没有查询到");
        Assert.isTrue(auditorsUser.getLocked() == 0, "该审核人已经离职或者被锁定！");
        //查询审核人的部门
        //OrganizationEntity organizationEntity = organizationService.getByIdHiber(auditorsUser.getOrgId());

        scProOrder.setAuditorId(auditorsUser.getId()); //审核人id
        scProOrder.setAuditorName(auditorsUser.getName());//审核人名称
        this.repository.saveOrUpdate(scProOrder);
    }
}
